package com.hantang.web.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;

import com.hantang.web.dao.ds.UserPO;
import com.hantang.web.data.UserData;

public class UserDao extends BaseDao {

	private static Logger logger = Logger.getLogger(UserDao.class);
	
	public static UserData convertPo2Data(UserPO po)
	{
		if(po == null){
			return null;
		}
		UserData data = new UserData();
		data.setCreateDate(po.getCreateDate());
		data.setEmail(po.getEmail());
		data.setName(po.getName());
		data.setPassword(po.getPassword());
		data.setPhone(po.getPhone());
		data.setRemarks(po.getRemarks());
		data.setType(po.getType());
		data.setUuid(po.getUuid());
		
		return data;
	}
	public static UserPO convertData2Po(UserData po)
	{
		if(po == null){
			return null;
		}
		UserPO data = new UserPO();
		data.setCreateDate(po.getCreateDate());
		data.setEmail(po.getEmail());
		data.setName(po.getName());
		data.setPassword(po.getPassword());
		data.setPhone(po.getPhone());
		data.setRemarks(po.getRemarks());
		data.setType(po.getType());
		data.setUuid(po.getUuid());
		
		return data;
	}
	
	public String saveData(UserData data)
	{
		if(data == null){
			logger.error("saveData, data is null!");
			return null;
		}
		UserPO po = convertData2Po(data);
		this.save(po);
		logger.info("saveData, return Id:" + po.getUuid());
		return po.getUuid();
	}

	@SuppressWarnings("unchecked")
	public String getUuidByName(String userName)
	{
		String data = null;
		try{
			this.openSession();
			Query query = session.createQuery("select u.uuid from UserPO as u where u.name = ?")
								.setString(0, userName);//.setInteger(1, count);
			
			List<String> results = query.list();
			if (!results.isEmpty()) {
				data = results.get(0);
			}		
		}catch(Exception e){
			logger.error(e.getStackTrace());
			e.printStackTrace();
		}finally{
			this.closeSession();			
		}
		logger.info("loadDataByName, userName " + userName);
		return data;
	}
	
	@SuppressWarnings("unchecked")
	public UserData loadDataByName(String userName)
	{
		UserData data = null;
		try{
			this.openSession();
			Query query = session.createQuery("select u from UserPO as u where u.name = ?")
								.setString(0, userName);//.setInteger(1, count);
			
			List<UserPO> results = query.list();
			if (!results.isEmpty()) {
				data = convertPo2Data(results.get(0));
			}		
		}catch(Exception e){
			logger.error(e.getStackTrace());
			e.printStackTrace();
		}finally{
			this.closeSession();			
		}
		logger.info("loadDataByName, userName " + userName);
		return data;
	}
	
	public UserData loadData(String uuid)
	{
		UserData data = null;
		UserPO po =(UserPO)this.get(UserPO.class, uuid);
		if(po != null)
		{
			data = convertPo2Data(po);
		}
		return data;
	}
	
}
